<template>
	<div class="h100" style="display: flex; flex-direction: row;justify-content: space-between;">
		<div class="h100" style="width:30%;" v-loading="loading">
			<el-form ref="form" :model="rowItem" label-width="300px" label-position="top" :disabled="!btnShow">
				<el-row :gutter="30">
					<el-col :span="8">
						<el-form-item label="轮次名称" prop="taskName">
							<el-input v-model="rowItem.taskName" placeholder="请输入轮次名称" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="轮次描述" prop="taskDesc">
							<el-input v-model="rowItem.taskDesc" placeholder="请输入轮次描述" />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="轮次开始时间" prop="startTime">
							<el-date-picker clearable v-model="rowItem.startTime" type="date" value-format="yyyy-MM-dd"
								style="width: 100%;" placeholder="请选择轮次开始时间" @change="setStartTime">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="center-box">
				<el-table ref="table" :data="rwList" @selection-change="handleSelectionChange" lazy :load="load"
					:tree-props="{children: 'children', hasChildren: 'hasChildren'}" row-key="id" default-expand-all>
					<el-table-column label="节点名称" align="left" prop="nodeName" width="150" fixed="left"
						show-overflow-tooltip />
					<el-table-column label="节点天数" align="left" prop="nodeDay" />
					<el-table-column label="前置任务" align="left" prop="startTime" show-overflow-tooltip>
						<template slot-scope="scope">
							{{getQianzhiName(scope.row.nodeQianzhi[scope.row.nodeQianzhi.length-1])}}
						</template>
					</el-table-column>
					<el-table-column label="起止日期" align="left" prop="startTime" width="140">
						<template slot-scope="scope">
							起：{{scope.row.startTime}}</br>止：{{scope.row.endTime}}
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="100" fixed="right">
						<template slot-scope="scope">
							<el-button size="mini" style="font-size: 18px;" type="text" icon="el-icon-info"
								v-hasPermi="['lanjing:template:edit']" @click="showItemForm(scope.row)"
								:disabled="showItem"><!-- 配置 --></el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<el-divider direction="vertical" />
		<div class="h100" style="flex: 1;">
			<formItem @ok="okItemForm" @close="hideItemForm" ref="formItem" :btnShow="btnShow"></formItem>
		</div>
	</div>
</template>

<script>
	import {
		getAction,
		postAction,
		editAction,
		removeAction,
		detailAction,
	} from "@/api/api";
	import mylog from '@/views/components/mylog.vue'
	import myDrawer from '@/views/components/myDrawer.vue'
	import formItem from '@/views/lanjing/atask/formItem.vue'
	import dept from '@/views/lanjing/task/dept.vue'
	import dayjs from "dayjs";
	// import {
	// 	mixin
	// } from '@/mixins/mixins';
	export default {
		dicts: ['model_type'],
		// mixins: [mixin],
		components: {
			mylog,
			myDrawer,
			formItem,
			dept
		},
		name: "modelForm",
		data() {
			return {
				rightView: true,
				optionValue: null,
				options: [],
				loading: false,
				rowItem: {
				},
				itemForm: null,
				//
				showItem: false,
				rwList: [],
				ids: [],
				single: [],
				multiple: [],
				temaplatePingfen: [],
				setDayLisy: [],
				deptList: [],
				btnShow: false,
			};
		},
		created() {
		},
		methods: {
			setRowInfo(row) {

				console.log('初始化获取父级信息', row)
				//初始化获取父级信息
				this.rowItem = {
					...row
				}
				this.btnShow = row.temaplateType == 1 ? false : true;
				if (row.temaplateTask) {
					let tree = JSON.parse(row.temaplateTask)
					this.temaplatePingfen = [...tree]
					this.setTimeForm()
				}
				if (row.temaplateBackup2) {
					let id = JSON.parse(row.temaplateBackup2)
					this.optionValue = id.id
				}
				this.getModelList();
				this.$nextTick(() => {
					let arr = []
					if (row.deptIds) {
						if (row.deptIds.indexOf(',') != -1) {
							arr = row.deptIds.split(',')
						} else {
							arr[row.deptIds]
						}
					}
					this.$refs.dept.showNode(arr, row.temaplateType == 1 ? true : false)
				})
			},
			//新增编辑节点内容
			showItemForm(row = null) {
				this.showItem = true
				if (row) {
					this.itemForm = {
						...row
					}
				} else {
					this.itemForm = null
				}
				this.$refs.formItem.show(row)
				this.$refs.formItem.qianzhi = [{
					nodeName: '根节点',
					id: 'root'
				}, ...this.rwList]
			},
			//添加下级节点内容
			addItemForm(row = null) {
				this.showItem = true
				let id = new Date().getTime()
				let obj = {
					parentId: row.id,
					id,
					pingfenList: [],
					yaoqiuList: []
				}
				if (row.ids) {
					obj.ids = [...row.ids, id]
				} else {
					obj.ids = [row.id, id]
				}
				this.$refs.formItem.show(obj)
				this.$refs.formItem.qianzhi = [{
					nodeName: '根节点',
					id: 'root'
				}, ...this.rwList]
				this.$refs.formItem.setModelData(this.rowItem.startTime, [...this.setDayLisy])

			},
			//添加节点内容
			hideItemForm() {
				this.showItem = false
				this.itemForm = null
			},
			okItemForm(row) {
				let arr = [...this.setDayLisy]
				if (!this.itemForm) {
					this.temaplatePingfen.push({
						...row
					})
					if (row.nodeQianzhi[row.nodeQianzhi.length - 1] == 'root') {
						row.startTime = this.rowItem.startTime
						row.endTime = dayjs(row.startTime, "YYYY-MM-DD").add(row.nodeDay, 'day').format("YYYY-MM-DD")
					} else {
						let obj = arr.find(v => v.id == e)
						row.startTime = dayjs(obj.endTime, "YYYY-MM-DD").add(1, 'day').format("YYYY-MM-DD")
						row.endTime = dayjs(row.startTime, "YYYY-MM-DD").add(row.nodeDay, 'day').format("YYYY-MM-DD")
					}
					arr.push(row)
					this.rwList = this.handleTree(arr)
				} else {
					let index = arr.findIndex(v => v.id == row.id)
					console.log(index)
					if (index != undefined) {
						arr[index] = row
					}
					this.rwList = this.handleTree(arr)
				}
				this.showItem = false;
			},
			editRowInfo(json) {
				editAction('/lanjing/template', {
					id: this.rowItem.id,
					temaplatePingfen: json
				}).then(res => {
					this.$message({
						type: 'success',
						message: '编辑成功!'
					});
					this.detailRowInfo(this.rowItem.id)
					this.$refs.formItem.close()
				})
			},
			detailRowInfo(id) {
				this.loading = true;
				console.log(id)
				this.rwList = []
				this.setDayLisy = []
				detailAction('/lanjing/template', id).then(async res => {
					this.loading = false;
					if (res.data.temaplatePingfen) {
						console.log('/lanjing/template', JSON.parse(res.data.temaplatePingfen))
						let tree = JSON.parse(res.data.temaplatePingfen)
						this.temaplatePingfen = [...tree]
						this.setTimeForm()

					} else {
						this.rwList = []
					}
				})
			},
			load(tree, treeNode, resolve) {
				console.log(tree, treeNode)
				// getAction(`${this.apiUrl}/list`, {
				// 	parentId: tree.id,
				// 	pageNum: 1,
				// 	pageSize: 999,
				// }).then(res => {
				// 	resolve(res.rows);
				// })
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			removeRw(id) {
				let arr = [...this.temaplatePingfen]
				arr = arr.filter(v => v.id != id)
				this.rwList = this.handleTree(arr)
			},
			getModelList() {
				getAction('/lanjing/template/list', {
					pageSize: 999,
					pageIndex: 1,
				}).then(res => {
					this.options = res.rows
				})
			},
			setDept(e) {
				console.log('deptId', e)
				this.deptList = e
				// if (e) {
				// 	this.$set(this.rowItem, 'deptId', e.toSting())
				// }
			},
			setTimeForm(e = 'root', endTime = null) {
				console.log(this.temaplatePingfen.length)
				if (endTime) {
					endTime = dayjs(endTime, "YYYY-MM-DD").add(1, 'day').format("YYYY-MM-DD")
				}
				let arr = this.temaplatePingfen.filter(v => v.nodeQianzhi[v.nodeQianzhi.length - 1] == e)
				arr.forEach(v => {
					v.startTime = e == 'root' ? this.rowItem.startTime : endTime;
					v.endTime = dayjs(v.startTime, "YYYY-MM-DD").add(v.nodeDay, 'day').format("YYYY-MM-DD")
					this.setDayLisy.push(v)
					if (this.temaplatePingfen.filter(d => d.nodeQianzhi[d.nodeQianzhi.length - 1] == v.id)) {
						this.setTimeForm(v.id, v.endTime)
					}
				})
				if (this.setDayLisy.length == this.temaplatePingfen.length) {
					console.log('setTimeForm', this.setDayLisy)
					let arrOver = [...this.setDayLisy]
					this.rwList = this.handleTree(arrOver)
					// this.$emit('ok',{
					// 	...this.rowItem,
					// 	deptId:this.deptList.toString(),
					// 	// templateId:this.optionValue,
					// 	templateId:JSON.stringify(this.setDayLisy)
					// })
				} else {
					console.log('setTimeForm', this.setDayLisy, this.setDayLisy.length, this.temaplatePingfen.length)
				}
			},
			getQianzhiName(e) {
				if (e == 'root') {
					return '根节点'
				} else {
					let obj = this.temaplatePingfen.find(v => v.id == e)
					if (obj) {
						return obj.nodeName
					} else {
						return '异常节点'
					}
				}
			},
			setStartTime(e) {
				console.log(e)
				this.$confirm('修改轮次开始时间将自动重新计算任务时长, 是否自动计算?', '自动计算节点时间', {
					confirmButtonText: '自动计算',
					cancelButtonText: '取消',
					type: 'success'
				}).then(() => {
					this.setDayLisy = []
					this.rwList = []
					this.setTimeForm()
				})
			},
			getDataObj() {
				// console.log({
				// 	...this.rowItem,
				// 	deptIds:this.deptList.toString(),
				// 	// templateId:this.optionValue,
				// 	templateId:JSON.stringify(this.setDayLisy)
				// })
				let obj = {}
				if (this.optionValue) {
					let data = this.options.find(v => v.id == this.optionValue)
					obj = {
						id: data.id,
						name: data.temaplateName
					}
				}
				this.$emit('ok', {
					...this.rowItem,
					temaplateBackup2: JSON.stringify(obj),
					deptIds: this.deptList.toString(),
					temaplateTask: JSON.stringify(this.setDayLisy)
				})


			}
		}
	};
</script>
<style scoped lang="scss">
	.el-divider--vertical {
		height: 100%;
		margin: 0 30px;
		display: inline-block;
	}

	.title-box {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30px;

		>span {
			font-weight: 500;
			font-size: 18px;
			line-height: 30px;
		}

	}

	.center-box {

		height: calc(100% - 60px);
	}
</style>